package jp.co.menox.controller.tmapp.lend;

import jp.co.menox.tmapp.service.LendingHistoryService;
import jp.co.menox.tmapp.util.AjaxResponse;
import jp.co.menox.tmcommon.common.DataConst;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.gson.Gson;

public class UpdateLendingHistoryStatusController extends Controller {

    @Override
    public Navigation run() throws Exception {
        //--------------------------------------------------------------------
        //  1. リクエストからパラメータ取得
        //--------------------------------------------------------------------
        long id = Long.valueOf(request.getParameter("id"));
        int currentStatus = Integer.valueOf(request.getParameter("status"));
        String sharingId = request.getParameter("sharing_id");
        
        int statusType;
        
        if (currentStatus == DataConst.STATUS_SYOUNINZUMI) {
            statusType = DataConst.STATUS_KASHIDASHITYU;
        } else if (currentStatus == DataConst.STATUS_KASHIDASHITYU) {
            statusType = DataConst.STATUS_HENKYAKUZUMI;
        } else {
            return null;
        }
        
        
        //--------------------------------------------------------------------
        //  2. ステータス更新
        //--------------------------------------------------------------------
        LendingHistoryService service = new LendingHistoryService();
        boolean ret = service.updateStatus(id, statusType, sharingId);
        
        
        //--------------------------------------------------------------------
        //  3. チャンネルにメッセージ送信
        //     Cross-Domain、かつ、Firefoxの場合、なぜかPUSH通知されないため、削除
        //--------------------------------------------------------------------
        //ChannelService channelService = ChannelServiceFactory.getChannelService();
        //channelService.sendMessage(new ChannelMessage(sharingId, "success"));
        
        
        //--------------------------------------------------------------------
        //  4. JSON変換
        //--------------------------------------------------------------------
        AjaxResponse ajaxResult = new AjaxResponse();
        ajaxResult.success = ret;
        String json = new Gson().toJson(ajaxResult);
        
        
        //--------------------------------------------------------------------
        //  4. レスポンス設定
        //--------------------------------------------------------------------
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, DELETE, OPTIONS");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(json);
        
        
        return null;
    }
}